<template>
	<view class="introScroll">
	
		<view class="topView">
			<view class="nav-back">
				<top-heigth></top-heigth>
				<uv-navbar :fixed="false" bg-color="rgba(0,0,0,0)" title="选择城市" :safeAreaInsetTop="false">
					<template v-slot:left>
						<view class="uv-nav-slot" @click="goback()">
							<image src="/static/image/go.png" style="width: 40rpx; height: 40rpx;" mode="" class="image-top"></image>
						</view>
					</template>
				</uv-navbar>
			</view>	
			<!-- 城市搜索输入框 -->
			<view class="serchView">
				<view class="serch">
					<image class="serchIconImage" src="/static/image/search.png"></image>
					<input @input="cityInputListener" adjust-position="false" class="serchInput" placeholder="搜索城市名" type="text" />
				</view>
			</view>
			
		</view>
		<!-- 右侧字母 -->
		<view class='city_right'>
			<text class='letter_item' :class="curLetter == item ? 'active' : ''" v-for='(item,index) in letter' :key='index' @tap.stop='letterTap(index)'>{{item}}</text>
		</view>
		<scroll-view scroll-with-animation="true" class="cityListView" scroll-y="true" :scroll-into-view="scrollId">
			<view v-if="!cityKeyValue">
				<!-- 定位城市-标题 -->
				<view class="nowCityTextTipsView">
					<text class="nowLocationCity">当前城市</text>
				</view>
				<!-- 定位城市-内容 -->
				<view class="againLocationView">
					<text class="loactionText" @click="indexCitys">{{nowCity}}</text>
					<text class="loactionStatusText">{{locationStatus}}</text>
					<image :animation="animation" @click="locationImageClick" class="refreshImage" src="/static/image/refreshIcon.png"></image>
				</view>
				<view class="line-block"></view>
				<!-- 热门城市 -->
				<text class="hotCityTips" :id="'re'">热门城市</text>
				<view class='new_city_box'>
					<text class='new_city_text' 
						v-for='(item,index) in hotCityList' 
						:key='index' 
						@tap.stop='cityTap(index)'
						:class="curHotCity == item.id ? 'active' : ''"
					>{{item.shortName}}</text>
				</view>
			</view>
			
			<!-- 城市列表 -->
			<view class="forCityView">
				<view class="forCityItem" v-for="(item,index) in allCityList" :key="index">
					<view v-if="item.show" :id="item.letter" class="letterItemFirst">{{item.letter}}</view>
					<text @click="cityItemClick(index)" class="itemCityContent">{{item.city}}</text>
					<view v-if="!item.last" class="line"></view>
				</view>
			</view>
			
		</scroll-view>
		
	</view>
</template>
 
 
<script>
	import { pinyin } from 'pinyin-pro' //汉字转拼音
	import TopHeigth from '@/components/TopHeigth.vue'
	export default {
		components: { TopHeigth },
		data() {
			return {
				nowCity: '北京',
				locationStatus: '定位成功',
				letter: [],
				//热门城市
				hotCityList: [],
				//全部城市
				allCityList: [],
				//滑动到指定位置
				scrollId: '',
				//动画
				animation: {},
				//接口请求的数据
				cityList: [],
				curHotCity: '',
				curLetter: '',
				cityKeyValue: '',
				indexCity:'',
				indexLng:'',
				indexLat:''
			}
		},
 
		onLoad(options) {
			
			//获取热门城市
			this.queryHotAndOpen()
			
			//获取全国城市
			this.getCityList()
			this.locationImageClick()
			
		},
 
		methods: {
			//获取热门城市
			queryHotAndOpen:function(){
				uni.$u.http.get('/api/shop/v1_0/tAppStaffRCA/queryHotAndOpen',{}).then((res) => {
					this.hotCityList = res.data.hot;
				})
			},
			//获取全国城市
			getCityList() {
				uni.$u.http.get('/api/shop/v1_0/tAppStaffRCA/queryTRegion',{}).then((res) => {
					if(res.code == 200){
						this.cityList = res.data || [];
						this.cityList.map(item => {
							//通过汉字转大写字母
							let firstName = item.shortName.substr(0,1);//首字
							let letter = pinyin(firstName, {toneType: 'none', pattern: 'first' }).toUpperCase();//大写字母
							this.letter.push(letter);
							item.city = item.shortName;
							item.letter = letter;
						})
						//城市排序
						var x = "letter";
						this.cityList.sort(function (a, b) {
							if (a[x] < b[x]) {
								return -1
							}
							if (a[x] > b[x]) {
								return 1
							}
							return 0;
						});
						this.letter = Array.from(new Set(this.letter)); //去重
						this.letter = this.letter.sort(); //排序
						this.formatCityData(this.cityList);
					}else{
						uni.showToast({
							icon: "none",
							title: res.message
						})
					}
				})
				
			},
			//拼音点击事件
			letterTap(index) {
				this.scrollId = this.letter[index];
				this.curLetter = this.letter[index];
			},
			
			//搜索
			cityInputListener(e) {
				this.cityKeyValue = e.detail.value
				let value = e.detail.value
				let cityAll = this.allCityList
				let newArray = []
				for (let i = 0; i < cityAll.length; i++) {
					if (cityAll[i].city.indexOf(value) != -1 || cityAll[i].letter == value.toUpperCase()) {
						newArray.push(cityAll[i])
					}
				}
				if (value == '') {
					this.formatCityData(this.cityList)
				} else {
					this.formatCityData(newArray)
				}
			},
			goback(){
				uni.navigateBack()
			},
			//定位
			locationImageClick() {
				var that = this
				this.animation = uni.createAnimation()
				this.animation.rotate(360).step()
				this.animation = this.animation.export()
				this.locationStatus = '定位中...'
				uni.getLocation({
					geocode: true, // 是否解析地址信息（返回详细格式化地址信息）
					success: res => {
						// 获取当前位置坐标
						console.log("获取定位信息失败",res.address);
						this.indexLng = res.longitude;
						this.indexLat = res.latitude;
						uni.request({
							url:"https://restapi.amap.com/v3/geocode/regeo?key=8bb5265417fbf03e07a85e276baa162d&location="+res.longitude+","+res.latitude+"&poitype=&radius=1000&extensions=base&roadlevel=0",
							success:(res) => {
									if (res.data.regeocode.addressComponent.province != undefined) {
										that.indexCity = res.data.regeocode.addressComponent;
										if( res.data.regeocode.addressComponent.city.length==0){
										that.nowCity = res.data.regeocode.addressComponent.province;	
										}else{
											that.nowCity = res.data.regeocode.addressComponent.city;
										}
										that.locationStatus = '定位成功'
								}
							}
						})
						
					},
					fail: res => {
						that.nowCity = '获取定位信息失败'
						console.log("获取定位信息失败");
					}
				});
 
			},
			
			//获取城市列表	
			formatCityData: function(array) {
				for (let i = 0; i < array.length; i++) {
					array[i].show = false;
					if (i == 0) {
						//第一条显示首字母
						array[i].show = true
					} else if (array[i].letter != array[i - 1].letter) {
						//首字母与上一条不一样需要显示
						array[i].show = true
						array[i - 1].last = true
					}
					if (array.length == 1) {
						array[0].last = true
					}
					array.show = false
				}
				this.allCityList = array
			},
 
			//城市条目点击
			cityItemClick(index) {
				var data = this.allCityList[index]
				// setTimeout(() => {
				// 	uni.$emit('selectCityData', data);
				// },500)
				// uni.navigateBack({
				// 	delta: 1,
				// })
				uni.setStorageSync("cityName",data.shortName)
				this.curHotCity = data.id;
				var locationInfo = {
					province: data.shortName,
					regName: data.regName,
					cityId: data.id,
					longitude: data.lng,
					latitude: data.lat,
				}
				var curMapLocaL = uni.getStorageSync('curMapLocaL');
				if(curMapLocaL && curMapLocaL.province == locationInfo.regName){
					locationInfo.longitude = curMapLocaL.longitude;
					locationInfo.latitude = curMapLocaL.latitude;
				}
				uni.setStorageSync('location', locationInfo);
				setTimeout(() => {
					uni.$emit('selectCityData', data);
				},500)
				uni.navigateBack({
					delta: 1,
				})
			},
			indexCitys(){
				this.allCityList.forEach((item,index)=>{
					if(this.nowCity == item.regName){
						var data = this.allCityList[index]
						// setTimeout(() => {
						// 	uni.$emit('selectCityData', data);
						// },500)
						// uni.navigateBack({
						// 	delta: 1,
						// })
						uni.setStorageSync("cityName",data.shortName)
						this.curHotCity = data.id;
						var locationInfo = {
							province: data.shortName,
							regName: data.regName,
							cityId: data.id,
							longitude: data.lng,
							latitude: data.lat,
						}
						var curMapLocaL = uni.getStorageSync('curMapLocaL');
						if(curMapLocaL && curMapLocaL.province == locationInfo.regName){
							locationInfo.longitude = curMapLocaL.longitude;
							locationInfo.latitude = curMapLocaL.latitude;
						}
						uni.setStorageSync('location', locationInfo);
						setTimeout(() => {
							uni.$emit('selectCityData', data);
						},500)
						uni.navigateBack({
							delta: 1,
						})
						
					}
			});

				// uni.setStorageSync("cityName",this.nowCity)
				// var locationInfo = {
				// 	province: this.indexCity.province,
				// 	regName: this.nowCity,
				// 	cityId: this.indexCity.adcode,
				// 	longitude: this.indexLng,
				// 	latitude: this.indexLat,
				// }
				// var curMapLocaL = uni.getStorageSync('curMapLocaL');
				// if(curMapLocaL && curMapLocaL.province == locationInfo.regName){
				// 	locationInfo.longitude = curMapLocaL.longitude;
				// 	locationInfo.latitude = curMapLocaL.latitude;
				// }
				// uni.setStorageSync('location', locationInfo);
				// setTimeout(() => {
				// 	uni.$emit('selectCityData', data);
				// },500)
				// uni.navigateBack({
				// 	delta: 1,
				// })
			},
			//热门城市点击
			cityTap(index) {
				var data = this.hotCityList[index]
				uni.setStorageSync("cityName",data.shortName)
				this.curHotCity = data.id;
				var locationInfo = {
					province: data.shortName,
					regName: data.regName,
					cityId: data.id,
					longitude: data.lng,
					latitude: data.lat,
				}
				var curMapLocaL = uni.getStorageSync('curMapLocaL');
				if(curMapLocaL && curMapLocaL.province == locationInfo.regName){
					locationInfo.longitude = curMapLocaL.longitude;
					locationInfo.latitude = curMapLocaL.latitude;
				}
				uni.setStorageSync('location', locationInfo);
				setTimeout(() => {
					uni.$emit('selectCityData', data);
				},500)
				uni.navigateBack({
					delta: 1,
				})
			},
		}
	}
</script>
 
<style>
	page {
		height: calc(100vh - 120px);
	}
	.introScroll {
		height: 100%;
		width: 100%;
		position: relative;
	}
 
	.topView {
		
	}
 
	.serchView {
		width: 100%;
		height: 110rpx;
		display: flex;
		flex-direction: column;
		background-color: #FFFFFF;
		align-items: center;
		justify-content: center;
	}
 
	.serch {
		width: 690rpx;
		height: 70rpx;
		background: #F7F7F7;
		border-radius: 35rpx;
		display: flex;
		flex-direction: row;
		align-items: center;
	}
 
	.serchIconImage {
		width: 30rpx;
		height: 26rpx;
		margin-left: 30rpx;
	}
 
	.serchInput {
		height: 70rpx;
		width: 600rpx;
		margin-left: 12rpx;
		font-size: 30rpx;
		color: #000000;
	}
 
	.nowCityTextTipsView {
		display: flex;
		flex-direction: column;
		justify-content: center;
		height: 50rpx;
		width: 100%;
		padding-bottom: 14rpx;
	}
 
	.nowLocationCity {
		line-height: 50rpx;
		font-size: 28rpx;
		color: #999999;
		margin-left: 40rpx;
		margin-top: 15rpx;
	}
 
	.againLocationView {
		height: 88rpx;
		display: flex;
		flex-direction: row;
		align-items: center;
		position: relative;
		width: 100%;
		background-color: #FFFFFF;
	}
 
	.loactionText {
		color: #129DFF;
		margin-left: 40rpx;
		font-weight: bold;
		font-size: 16px;
		color: #333333;
	}
 
	.loactionStatusText {
		margin-left: 50rpx;
		font-size: 30rpx;
		color: #999999;
	}
 
	.refreshImage {
		position: absolute;
		right: 40rpx;
		padding: 10rpx;
		width: 38rpx;
		height: 38rpx;
	}
 
	.cityListView {
		display: flex;
		flex-direction: column;
		height: 100%;
		position: relative;
		overflow: scroll;
		background: #fff;
	}
 
	.city_right {
		z-index: 99;
		width: 60rpx;
		display: flex;
		height: 100%;
		position: absolute;
		right: 0;
		flex-direction: column;
		justify-content: center;
		top: 120rpx;
	}
 
	.letter_item {
		display: block;
		font-size: 20rpx;
		color: #666;
		text-align: center;
		padding-left: 20rpx;
		padding-top: 5rpx;
		font-weight: 400;
		font-size: 12px;
		color: #999999;
	}
	.letter_item.active {
		color: #27A0FF;
		font-weight: bold;
	}
	.hotCityTips {
		margin-left: 20px;
		margin-top: 16px;
		font-size: 14px;
		color: #999999;
		display: block;
	}
 
	.new_city_box {
		margin-top: 26rpx;
		display: flex;
		flex-wrap: wrap;
		padding: 0 60rpx 0 20rpx;
	}
 
	.new_city_text {
		width: 29%;
		height: 40px;
		background: #F8F8F8;
		border-radius: 4px;
		line-height: 40px;
		margin: 5px;
		text-align: center;
	}
	 .new_city_text.active {
		background: rgba(39,160,255,0.15);
		border: 1px solid #27A0FF;
		color: #27A0FF;
	 }
	.forCityView {
		width: 100%;
		padding-bottom: 30rpx;
		padding-top: 15px;
	}
 
	.forCityItem {
		display: flex;
		flex-direction: column;
	}
 
	.letterItemFirst {
		height: 49rpx;
		padding-left: 40rpx;
		font-size: 30rpx;
		line-height: 49rpx;
		color: #000;
		width: 100%;
	}
 
	.itemCityContent {
		display: inline-block;
		width: 100%;
		height: 88rpx;
		font-size: 34rpx;
		color: #000000;
		padding-left: 38px;
		background-color: #FFFFFF;
		line-height: 88rpx;
	}
 
	.line {
		width: 82%;
		height: 1rpx;
		background-color: #ebebeb;
		margin-left: 38px;
	}
	.search-head{
		position: relative;
		margin-top: 28px;
		display: flex;
	}
	.image-top{
		margin-top: 8px;
	}
	.line-block{
		width: 100%;
		height: 12px;
		background: #f7f7f7;
	}
</style>